# backend/crud/user_crud.py
from sqlalchemy.orm import Session
from datetime import datetime
from backend.models import User
from backend.utils.security import get_password_hash


def get_user(db: Session, user_id: int):
    return db.query(User).filter(User.id == user_id).first()


def get_user_by_username(db: Session, username: str):
    return db.query(User).filter(User.username == username).first()


def get_all_users(db: Session):
    """获取所有用户"""
    return db.query(User).all()


def create_user(db: Session, username: str, password: str, full_name: str):
    # 使用新的密码哈希函数
    hashed_password = get_password_hash(password)

    db_user = User(
        username=username,
        hashed_password=hashed_password,
        full_name=full_name,
        created_at=datetime.utcnow()
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def update_user_password(db: Session, user_id: int, new_password: str):
    db_user = get_user(db, user_id)
    if db_user:
        # 使用新的密码哈希函数
        db_user.hashed_password = get_password_hash(new_password)
        db.commit()
        db.refresh(db_user)
    return db_user
